//
//  FacebookAccount.m
//  FacebookAccount
//
//  Created by wyht－ios－dev on 16/11/16.
//  Copyright © 2016年 WYHT. All rights reserved.
//

#import "FacebookAccount.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "OpenSDK_Enum.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_PayResData.h"
#import "OpenSDK_ReqDataGenerator.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_Delegate.h"
#import "OpenSDK_StatusManager.h"
#import "LocalizationManager.h"

@implementation FacebookAccount {
    AKFAccountKit *accountKit;
    UIViewController<AKFViewController> *pendingLoginViewController;
    id<OpenSDK_Delegate> userDelegate;
}

-(void) initInfo {
    [OpenSDK_EventManager addObsver:self selector:@selector(initSDK) name:OPENSDK_EVENT_INIT object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(loginWithData:) name:OPENSDK_EVENT_LOGIN object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(logout) name:OPENSDK_EVENT_LOGOUT object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_options:) name:OPENSDK_EVENT_APPLICATION_OPENURL_OPTIONS object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_openURL_sourceApplication_annotation:) name:OPENSDK_EVENT_APPLICATION_OPENURL_SOURCEAPPLICATION_ANNOTATION object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(application_didFinishLaunchingWithOptions:) name:OPENSDK_EVENT_APPLICATION_DIDFINISHLAUNCHINGWITHOPTIONS object:nil className:@"FacebookAccount"];
    [OpenSDK_EventManager addObsver:self selector:@selector(applicationDidBecomeActive) name:OPENSDK_EVENT_APPLICATIONDIDBECOMEACTIVE object:nil className:@"FacebookAccount"];
}

-(void) initSDK {
    //初始化accountKit
    accountKit=[[AKFAccountKit alloc] initWithResponseType:AKFResponseTypeAccessToken];
    pendingLoginViewController = [accountKit viewControllerForLoginResume];
}

-(void) logout {
    //退出当前所有账号,包括facebook和accountkit
    [accountKit logOut];
}

//登录
-(void) loginWithData:(NSNotification*) notification {
    if([[[notification object] objectForKey:OpenSDK_E_LOGIN] isEqualToString:OpenSDK_L_FACEBOOKSDK]) {
        userDelegate=[[notification object] objectForKey:OpenSDK_L_USERDELEGATE];
        UIViewController *view=(UIViewController *)[[notification object] objectForKey:OpenSDK_L_VIEWCONTROLLER];
        if([[[notification object] objectForKey:OpenSDK_L_FACEBOOK_TYPE] isEqualToString:OpenSDK_L_FACEBOOK_ACCOUNT]) {
            [self loginWithAccount:view];
            NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋开始Facebook账号登录");
        }
        if([[[notification object] objectForKey:OpenSDK_L_FACEBOOK_TYPE] isEqualToString:OpenSDK_L_FACEBOOK_PHONE]) {
            [self loginWithPhone:view];
        }
        if([[[notification object] objectForKey:OpenSDK_L_FACEBOOK_TYPE] isEqualToString:OpenSDK_L_FACEBOOK_EMAIL]) {
            [self loginWithEmail:view];
        }
    }
}

//短信登录
-(void) loginWithPhone:(UIViewController *) curViewController {
    if(accountKit!=nil) {
        //不考虑已经登录过的情况
        NSString *inputState = [[NSUUID UUID] UUIDString];
        UIViewController<AKFViewController> *viewController = [accountKit viewControllerForPhoneLoginWithPhoneNumber:nil state:inputState];
        viewController.enableSendToFacebook = YES;
        viewController.delegate=self;
        [curViewController presentViewController:viewController animated:YES completion:NULL];
    }
}

//邮箱登录
-(void) loginWithEmail:(UIViewController *) curViewController {
    if(accountKit!=nil) {
        //不考虑已经登录过的情况
        NSString *inputState = [[NSUUID UUID] UUIDString];
        UIViewController<AKFViewController> *viewController = [accountKit viewControllerForEmailLoginWithEmail:nil state:inputState];
        viewController.delegate=self;
        [curViewController presentViewController:viewController animated:YES completion:NULL];
    }
}

//Facebook账户登录
-(void) loginWithAccount:(UIViewController *) curViewController {
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
    [login logInWithReadPermissions: @[@"public_profile"] fromViewController:curViewController
         handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
             if (error) {
                 NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋Facebook账号登录失败");
                 //登录错误
                 [[[UIAlertView alloc]initWithTitle:[LocalizationManager getValueByKey:OpenSDK_LOCALIZATION_WARN2] message:[error localizedDescription] delegate:nil cancelButtonTitle:[LocalizationManager getValueByKey:OpenSDK_LOCALIZATION_OK] otherButtonTitles:nil, nil] show];
             } else if (result.isCancelled) {
                 NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋Facebook账号登录取消");
                 //用户取消登录
             } else {
                 NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋Facebook账号登录成功");
                 //登录成功
                 NSMutableDictionary *data=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
                 [data setObject:OpenSDK_S_FACEBOOKSDK forKey:OpenSDK_S_OAUTH_TYPE];
                 [data setObject:result.token.tokenString forKey:OpenSDK_S_ACCESS_TOKEN];
                 [data setObject:result.token.userID forKey:OpenSDK_S_PLATFORM_UID];
                 [data setObject:@"1.0" forKey:OpenSDK_S_PLATFORM_VERSION];
                 [[OpenSDK_ReqDataGenerator getInstance] restoreSDKParameters:data];
                 NSString *dataStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:data];
                 
                 [self loginWithOtherSDK:dataStr userDelegate:userDelegate];
             }
         }];
}

- (void) viewController:(UIViewController<AKFViewController> *)viewController didCompleteLoginWithAccessToken:(id<AKFAccessToken>)accessToken state:(NSString *)state {
    //facebook accountkit 登录成功
    NSMutableDictionary *data=[OpenSDK_ReqDataGenerator generateInitDataWithInfo];
    [data setObject:OpenSDK_S_FACEBOOKSDK_ACCOUNTKIT forKey:OpenSDK_S_OAUTH_TYPE];
    [data setObject:[accessToken tokenString] forKey:OpenSDK_S_ACCESS_TOKEN];
    [data setObject:[accessToken accountID] forKey:OpenSDK_S_PLATFORM_UID];
    [data setObject:@"1.0" forKey:OpenSDK_S_PLATFORM_VERSION];
    [[OpenSDK_ReqDataGenerator getInstance] restoreSDKParameters:data];
    NSString *dataStr=[OpenSDK_ReqDataGenerator generateDataByDictionary:data];
    
    [self loginWithOtherSDK:dataStr userDelegate:userDelegate];
}

- (void)viewController:(UIViewController<AKFViewController> *)viewController didFailWithError:(NSError *)error {
    //facebook accountkit 登录失败
    [[[UIAlertView alloc]initWithTitle:[LocalizationManager getValueByKey:OpenSDK_LOCALIZATION_WARN2] message:[error localizedDescription] delegate:nil cancelButtonTitle:[LocalizationManager getValueByKey:OpenSDK_LOCALIZATION_OK] otherButtonTitles:nil, nil] show];
}

- (void)viewControllerDidCancel:(UIViewController<AKFViewController> *)viewController {
    //facebook accountkit 取消登录
}

-(void) applicationDidBecomeActive {
    [FBSDKAppEvents activateApp];
}

-(void) application_didFinishLaunchingWithOptions:(NSNotification*) notification {
    NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋application_didFinishLaunchingWithOptions");
    [[FBSDKApplicationDelegate sharedInstance] application:[[notification object] objectForKey:OpenSDK_E_APPLICATION]
                             didFinishLaunchingWithOptions:[[notification object] objectForKey:OpenSDK_E_DIDFINISHLAUNCHWITHOPTIONS]];
}

-(void) application_openURL_sourceApplication_annotation:(NSNotification*) notification {
    NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋application_openURL_sourceApplication_annotation");
    [[FBSDKApplicationDelegate sharedInstance] application:[[notification object] objectForKey:OpenSDK_E_APPLICATION]
                                                          openURL:[[notification object] objectForKey:OpenSDK_E_OPENURL]
                                                sourceApplication:[[notification object] objectForKey:OpenSDK_E_SOURCEAPPLICATION]
                                                       annotation:[[notification object] objectForKey:OpenSDK_E_ANNOTATION]];
}

-(void) application_openURL_options:(NSNotification*) notification {
    NSLog(@"facebook＋＋＋＋＋＋＋＋＋＋＋＋＋＋application_openURL_options");
    [[FBSDKApplicationDelegate sharedInstance] application:[[notification object] objectForKey:OpenSDK_E_APPLICATION]
                                                   openURL:[[notification object] objectForKey:OpenSDK_E_OPENURL]
                                         sourceApplication:[[notification object] objectForKey:OpenSDK_E_OPTIONS][UIApplicationOpenURLOptionsSourceApplicationKey]
                                                annotation:[[notification object] objectForKey:OpenSDK_E_OPTIONS][UIApplicationOpenURLOptionsAnnotationKey]];
}

@end
